package fr.norsys.mapper.console.service;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;

import org.apache.commons.lang.StringUtils;

import fr.norsys.mapper.console.model.Connection;
import fr.norsys.mapper.console.model.Resource;
import fr.norsys.mapper.console.utils.PasswordEncoder;

public class ValidationHelperImpl implements ValidationHelper {
	public boolean isConnectionValid(Connection connection) {
		DirContext context = null;
		try {
			Hashtable env = new Hashtable();
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.PROVIDER_URL, connection.getUrl());
			env.put(Context.SECURITY_PRINCIPAL, connection.getUser());
			env.put(Context.SECURITY_CREDENTIALS, connection.getPass());
			env.put("com.sun.jndi.ldap.connect.timeout","180");
			context = new InitialDirContext(env);
			context.close();
		} catch(NamingException e) {
			if(context != null)
				{
				try {context.close();} catch (NamingException e1) {}
				}
			return false;
		}
		return true;
	}
	public boolean isSearchResourceValid(Resource resource, Connection connection) {
		DirContext context = null;
		try {
			Hashtable env = new Hashtable();
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.PROVIDER_URL, connection.getUrl());
			env.put(Context.SECURITY_PRINCIPAL, connection.getUser());
			env.put(Context.SECURITY_CREDENTIALS, connection.getPass());
			env.put("com.sun.jndi.ldap.connect.timeout","180");
			context = new InitialDirContext(env);
			SearchControls ctls = new SearchControls();
			ctls.setCountLimit(1);
			ctls.setReturningObjFlag(true);
			ctls.setDerefLinkFlag(true);
			ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
			String filter = "(objectClass=*)";
			if(resource.getFilter()!=null && !"".equals(resource.getFilter().trim()))
				filter = populateFilter(resource.getFilter());
			NamingEnumeration ne = context.search(resource.getBaseDn(), filter, ctls);
			if(ne!=null && ne.hasMore())
				return true;
			else
				return false;
		} catch(NamingException e) {
			return false;
		} finally {
			if(context != null)
			{
				try {context.close();} catch (NamingException e1) {}
			}
		}
	}
	public String populateFilter(String filt) {
		String filter = filt;
		while(filter.indexOf("${") > -1) {
			String tmp=filter.substring(filter.indexOf("${"),filter.indexOf("}"))+"}";
			filter = StringUtils.replace(filter,tmp,"*");
		}
		return filter;
	}
}